<template>
  <div class="project-div" v-if="dataSource.length > 0" ref="dragContainer">
    <Container orientation="horizontal" @drop="onDrop">
      <Draggable
        v-for="(item, index) in dataSource"
        :key="item.index"
        @mousedown="startDrag(index)"
        @mousemove="doDrag"
        @mouseup="endDrag"
      >
        <div
          :class="{
            highlighted: selectedId && selectedId === index,
            itemDiv: true,
          }"
        >
          <project-item
            :key="item?.id"
            :data="item"
            :hightlight-change="selectedId === index ? true : false"
          />
        </div>
      </Draggable>
    </Container>
  </div>
  <!-- 无数据时 -->
  <div
    v-else
    style="
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100%;
    "
  >
    <a-spin :spinning="loading">
      <a-empty
        :image="notData"
        :description="loading ? '加载中...' : '暂无数据'"
      />
    </a-spin>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick } from 'vue'
import ProjectItem from './project-item.vue'
import {
  useDataSource,
  useDataSourceManager,
  useLoading,
} from './provide-context.js'
import notData from '@/assets/images/not-data.png'
import { folderResort } from '@/api/catalog-personal'
import { Container, Draggable } from 'vue3-smooth-dnd'

// 外部参数
let props = defineProps({
  scrollRight: { type: Boolean, default: () => false },
})
// 新增项目之后滚动条默认拉到最右
watch(
  () => props.scrollRight,
  async (n, o) => {
    await nextTick()
    setTimeout(() => {
      if (dragContainer.value) {
        dragContainer.value.scrollLeft = dragContainer.value.scrollWidth
      }
    }, 1200)
  },
  { deep: true, immediate: false },
)
/**
 * 全局数据
 */

let { update } = useDataSourceManager()
let loading = useLoading()
update()
let dataSource = useDataSource()
const selectedId = ref(null)

let isDraging = ref(false)
let currentDrag = ref(null)
function startDrag(index) {
  isDraging.value = true
  currentDrag.value = index
}
function endDrag() {
  isDraging.value = false
  selectedId.value = null
  currentDrag.value = null
}
function doDrag() {
  if (isDraging.value) {
    selectedId.value = currentDrag.value
  }
}
// 项目拖曳排序
function applyDrag(arr, dragResult) {
  const { removedIndex, addedIndex, payload } = dragResult

  if (removedIndex === null && addedIndex === null) return arr
  const result = [...arr]
  let itemToAdd = payload

  if (removedIndex !== null) {
    itemToAdd = result.splice(removedIndex, 1)[0]
  }
  if (addedIndex !== null) {
    result.splice(addedIndex, 0, itemToAdd)
  }
  selectedId.value = null
  currentDrag.value = null
  return result
}
async function onDrop(dropResult) {
  const { removedIndex, addedIndex, payload } = dropResult
  dataSource.value = applyDrag(dataSource.value, dropResult)

  // todo 保存顺序改变
  try {
    let params = []
    let sort = 1
    dataSource.value.forEach(item => {
      params.push({ id: item.id, sort })
      sort = sort + 1
    })
    loading.value = true
    await folderResort(params)
    loading.value = false
  } catch (e) {
    loading.value = false
  }
}

const dragContainer = ref(null)

const handleClick = event => {
  if (!dragContainer?.value?.contains(event.target)) {
    // 点击发生在dragContainer外部
    selectedId.value = null
    currentDrag.value = null
  }
}

onMounted(() => {
  // 添加事件监听
  window.addEventListener('click', handleClick)
})
</script>
<style scoped lang="less">
.itemDiv {
  margin: 15px 32px 0px 0px;
  width: 300px;
  min-height: 380px;
  max-height: 390px;
  // 配合使itemDiv占满
  display: flex;
  flex-direction: column;
}
.highlighted {
  // background-color: #0086ff0f; /* Highlight color */
}

/* 滚动条整体部分 */
// ::-webkit-scrollbar {
//   width: 12px; /* 滚动条的宽度 */
//   height: 12px; /* 滚动条的高度 */
// }
.project-div {
  display: flex;
  overflow-x: auto;
  width: 100%;
}
</style>
